var httpRequest = require('request');
var AsyncLock = require('async-lock');

const {
    getSonList,
    getGrandSonList,
    getPlayerHome,
    getSharePoster,
    getMasterInfo,
    withdrawLog,
    playerWithdraw,
    withdrawInfoAction
} = require('../lib/action');

const {
    getUserInfo,
} = require('../lib/api');

const {
    Msg,
    Code,
    LockKey
} = require('../lib/consts');

module.exports = function (app) {
    return new Handler(app);
};
const Handler = function (app) {
    this.app = app;
};

const handler = Handler.prototype;


const lock = new AsyncLock({timeout: 1000});

/**
 * 获取徒弟信息
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sGetSon = async function (msg, session, next) {
    let uid = session.get('uid');
    let pageNum = Number(msg.page_num) < 1 ? 1 : Number(msg.page_num);
    let users = await getSonList.call(this, {session, uid, pageNum});

    next(null, {code: Code.SUC, data: users});
}

/**
 * 获取徒孙信息
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sGetGrandSon = async function (msg, session, next) {
    let uid = session.get('uid');
    let pageNum = Number(msg.page_num) < 1 ? 1 : Number(msg.page_num);
    let users = await getGrandSonList.call(this, {session, uid, pageNum});

    next(null, {code: Code.SUC, data: users});
}

/**
 * 获取师傅信息
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sGetMaster = async function (msg, session, next) {
    let uid = session.get('uid');
    try {
        let parent = await getMasterInfo.call(this, {session, uid});
        next(null, {code: Code.SUC, data: parent});
    } catch (err) {
        next(null, {code: Code.ERR, data: err.toString()});
    }
}

/**
 * 获取收益主页信息
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sPlayerHome = async function (msg, session, next) {
    let uid = session.get('uid');
    let data = await getPlayerHome.call(this, {session, uid});
    next(null, {code: Code.SUC, data: data});
}

/**
 * 获取分享图
 * @param msg
 * @param session
 * @param next
 */
handler.c2sSharePoster = async function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');
    let userInfo = await getUserInfo.call(this, session, uid);
    if (!userInfo) {
        next(null, {
            code: Code.ERR,
            msg: Msg.USER_NOT_FOUND,
        });
        return;
    }

    // if (userInfo.share_poster) {
    //     next(null, {
    //         code: Code.SUC,
    //         msg: Msg.RESULT_SUCCESS,
    //         data: userInfo.share_poster
    //     });
    //     return;
    // }

    httpRequest({
        url: 'http://oil.njtrtw.ltd/wechat/qrcode?id=' + uid,
        method: "GET"
    }, async function (error, response, body) {

        if (response.statusCode != 200) {
            console.log('c2sSharePoster error: ' + error)
            console.error('c2sSharePoster 执行失败 response.statusCOde' + response.statusCode)
            next(null, {
                code: Code.ERR,
                msg: Msg.NET_WORK_BUSY,
            });
            return;
        } else {
            var queryData = JSON.stringify({
                background: 'https://qiqiutree.leyougame.cc/oil_background2.png',
                dress: [
                    {
                        type: 'image',
                        url: body, //二维码地址
                        xposition: 245,
                        yposition: 1085,
                        gravity: "NorthWest",
                        ws: 0.35
                    },
                    {
                        type: 'text',
                        content: 'ID: ' + userInfo.invite_id,
                        font_size: 550,
                        color: '#fff',
                        xposition: 210,
                        yposition: 60,
                        gravity: "NorthWest",
                    },
                    {
                        type: 'image',
                        url: userInfo.avatar ? userInfo.avatar : 'https://qiqiutree.leyougame.cc/default_avatar.jpg',
                        xposition: 85,
                        yposition: 50,
                        gravity: "NorthWest",
                        ws: 0.15
                    },
                    {
                        type: 'text',
                        content: userInfo.nickname ? userInfo.nickname : '石油大亨',
                        font_size: 550,
                        color: '#fff',
                        xposition: 210,
                        yposition: 100,
                        gravity: "NorthWest",
                    }
                ]
            });

            await httpRequest({
                url: 'https://graphs.tsingmuth.com/graph/compound',
                method: "POST",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
                body: queryData,
            }, function (error, response, body) {
                if (response.statusCode != 200) {
                    console.error('compoundPoster 执行失败 response.statusCode' + response.statusCode)
                    throw new Error(Msg.NET_WORK_BUSY);
                } else {
                    if (body.code != '000') {
                        next(null, {
                            code: Code.ERR,
                            msg: Msg.NET_WORK_BUSY,
                        });
                        return;
                    } else {
                        //更新内存
                        self.app.userRemote(uid, "set", [uid, "user.share_poster", body.data]);
                        next(null, {
                            code: Code.SUC,
                            msg: Msg.RESULT_SUCCESS,
                            data: body.data
                        });
                        return;
                    }
                }
            });
        }
    });
}

/**
 * 获取邀请地址
 * @param msg
 * @param session
 * @param next
 */
handler.c2sGetInvitePath = async function (msg, session, next) {
    var self = this;
    var uid = session.get('uid');

    next(null, {
        code: Code.SUC,
        msg: Msg.RESULT_SUCCESS,
        data: "http://oil.njtrtw.ltd/wechat?id=" + encodeURI(uid)
    });
    return;
}

/**
 * 用户提现
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sWithdraw = async function (msg, session, next) {
    let self = this;
    let uid = session.get('uid');
    let cate = msg.cate;
    //获取任务锁
    lock.acquire(LockKey.DAILY_MISSION_LOCK + uid, async function () {
        try {
            await playerWithdraw.call(self, {session, uid, cate});

            next(null, {
                code: Code.SUC,
                msg: Msg.RESULT_SUCCESS
            });
            return;
        } catch (err) {
            next(null, {
                code: Code.ERR,
                msg: err.toString()
            });
            return;
        }
    }, function (err, ret) {
        //锁释放
        if (!!err) {
            console.error('c2sWithdraw err 2:' + err)
        }
    })
}

/**
 * 获取提现信息
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sWithdrawInfo = async function (msg, session, next) {
    let self = this;
    let uid = session.get('uid');
    let info = await withdrawInfoAction.call(self, {session, uid});

    next(null, {
        code: Code.SUC,
        msg: Msg.RESULT_SUCCESS,
        data: info
    });
    return;
}

/**
 * 获取用户提现记录
 * @param msg
 * @param session
 * @param next
 * @returns {Promise<void>}
 */
handler.c2sWithdrawLog = async function (msg, session, next) {
    let self = this;
    let uid = session.get('uid');
    let pageNum = msg.page_num;
    let pageSize = msg.page_size > 10 ? 10 : msg.page_size;

    let data = await withdrawLog.call(self, {session, uid, pageNum, pageSize});
    next(null, {code: Code.SUC, msg: Msg.RESULT_SUCCESS, data: data});
}